<template>
  <div class="my-flex-column w100 h100">
    <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
      <el-form :inline="true" @submit.stop.prevent>
        <el-form-item label="设备配方代号">
          <my-select-input v-model="state.pageInput.dynamicFilter" :filters="state.filters" @search="onQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="ele-Search" @click="onQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="my-fill mt8" shadow="never">
      <div class="my-tools-box mb8 my-flex my-flex-between">
        <div>
          <el-button v-auth="'api:industry:device-formula:add'" type="primary" icon="ele-Plus" @click="onAdd"> 新增
          </el-button>
          <el-button v-auth="'api:industry:device-formula:add'" type="primary" icon="ele-CopyDocument" @click="onCopy">
            复制配方
          </el-button>
        </div>
        <div>
          <el-tooltip effect="dark" :content="state.showQuery ? '隐藏查询' : '显示查询'" placement="top">
            <el-button :icon="state.showQuery ? 'ele-ArrowUp' : 'ele-ArrowDown'" circle
              @click="state.showQuery = !state.showQuery" />
          </el-tooltip>
        </div>
      </div>
      <el-table ref="tableRef" v-loading="state.loading" :data="state.deviceFormulaListData" @sort-change="onSortChange"
        row-key="id" border>
        <el-table-column type="selection" />
        <el-table-column prop="formulaCode" label="配方代号" width="100" show-overflow-tooltip />
        <el-table-column prop="formulaName" label="配方名称" width="100" show-overflow-tooltip />
        <el-table-column prop="formulaOrder" label="配方序号" width="100" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="80" align="center" sortable="custom" show-overflow-tooltip />
        <el-table-column label="关联点位" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <el-switch v-if="auth('api:industry:device-formula:set-link-point-enable')" v-model="row.linkPoint"
              :loading="row.loading" :active-value='true' :inactive-value='false' inline-prompt active-text="开启"
              inactive-text="关闭" :before-change="() => onSetLinkPointEnable(row)" />
            <template v-else>
              <el-tag type="success" v-if="row.linkPoint">启用</el-tag>
              <el-tag type="danger" v-else>禁用</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center" fixed="right">
          <template #default="{ row }">
            <el-switch v-if="auth('api:industry:device-formula:set-enable')" v-model="row.enabled"
              :loading="row.loading" :active-value='true' :inactive-value='false' inline-prompt active-text="开启"
              inactive-text="关闭" :before-change="() => onSetEnable(row)" />
            <template v-else>
              <el-tag type="success" v-if="row.enabled">启用</el-tag>
              <el-tag type="danger" v-else>禁用</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" header-align="center" align="center" fixed="right">
          <template #default="{ row }">
            <el-button v-auth="'api:industry:device-formula:update'" icon="ele-EditPen" size="small" text type="primary"
              @click="onEdit(row)">编辑</el-button>
            <my-dropdown-more v-auths="['api:industry:device-formula:soft-delete']">
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="auth('api:industry:device-formula:soft-delete')"
                    @click="onDelete(row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </my-dropdown-more>
          </template>
        </el-table-column>
      </el-table>
      <div class="my-flex my-flex-end" style="margin-top: 10px">
        <el-pagination v-model:currentPage="state.pageInput.currentPage" v-model:page-size="state.pageInput.pageSize"
          :total="state.total" :page-sizes="[10, 20, 50, 100]" small background @size-change="onSizeChange"
          @current-change="onCurrentChange" layout="total, sizes, prev, pager, next, jumper" />
      </div>
    </el-card>
    <DeviceFormulaForm ref="deviceFormulaFormRef" :title="state.deviceFormulaFormTitle"></DeviceFormulaForm>
    <DeviceFormulaCopyForm ref="deviceFormulaCopyFormRef" :title="state.deviceFormulaCopyFormTitle">
    </DeviceFormulaCopyForm>
    <MyFilterDialog ref="myFilterDialogRef" :fields="state.filters" @sure="onFilterSure"></MyFilterDialog>
  </div>
</template>
<script setup lang="ts" name="industry/device-formula">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent } from 'vue'
import { PageInputDeviceFormulaGetPageInput, DeviceFormulaGetPageOutput, DeviceFormulaGetOutput, SortInput } from '/@/api/industry/data-contracts'
import { DeviceFormulaApi } from '/@/api/industry/DeviceFormula'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'
import { ElTable } from 'element-plus'

const MyDropdownMore = defineAsyncComponent(() => import('/@/components/my-dropdown-more/index.vue'))
const MyFilterDialog = defineAsyncComponent(() => import('/@/components/my-filter/dialog.vue'))
const MySelectInput = defineAsyncComponent(() => import('/@/components/my-select-input/index.vue'))
const DeviceFormulaForm = defineAsyncComponent(() => import('./compoents/device-formula-form.vue'))
const DeviceFormulaCopyForm = defineAsyncComponent(() => import('./compoents/device-formula-form-copy.vue'))
const deviceFormulaFormRef = ref()
const deviceFormulaCopyFormRef = ref()
const { proxy } = getCurrentInstance() as any
const getSortList = (data: { prop: string; order: any }) => {
  return [
    {
      propName: data.prop,
      order: data.order === 'ascending' ? 0 : data.order === 'descending' ? 1 : undefined,
    },
  ] as [SortInput]
}

const defalutSort = { prop: 'sort', order: 'ascending' }
const state = reactive({
  loading: false,
  showQuery: true,
  deviceFormulaFormTitle: '',
  deviceFormulaCopyFormTitle: '',
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
    sortList: getSortList(defalutSort),
    filter: {
    },
    dynamicFilter: {
    },
  } as PageInputDeviceFormulaGetPageInput,
  deviceFormulaListData: [] as Array<DeviceFormulaGetPageOutput>,
  filters: [
    {
      field: 'formulaCode',
      operator: 'Contains',
      description: '配方代号',
      componentName: 'el-input',
      defaultSelect: true,
    },
    {
      field: 'formulaName',
      operator: 'Contains',
      description: '配方名称',
      componentName: 'el-input',
      defaultSelect: false,
    },
  ] as Array<DynamicFilterInfo>,
})

onMounted(() => {
  onQuery()
  eventBus.off('refreshDeviceFormula')
  eventBus.on('refreshDeviceFormula', async () => {
    onQuery()
    eventBus.emit('refreshFormulaDetail')

  })
})

onBeforeMount(() => {
  eventBus.off('refreshDeviceFormula')
})

const onSortChange = (data: { column: any; prop: string; order: any }) => {
  state.pageInput.sortList = getSortList(data)
  onQuery()
}
//查询分页
const onQuery = async () => {
  state.loading = true
  const res = await new DeviceFormulaApi().getPage(state.pageInput).catch(() => {
    state.loading = false
  })

  state.deviceFormulaListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}
const onFilterSure = (dynamicFilter: any) => {
  state.pageInput.dynamicFilter = dynamicFilter
  onQuery()
}
//新增
const onAdd = (row: DeviceFormulaGetOutput) => {
  state.deviceFormulaFormTitle = `新增配方信息`
  deviceFormulaFormRef.value.open()
}
//复制配方
const onCopy = () => {
  state.deviceFormulaCopyFormTitle = `新增配方信息`
  deviceFormulaCopyFormRef.value.open()
}
//修改
const onEdit = (row: DeviceFormulaGetOutput) => {
  state.deviceFormulaFormTitle = `编辑配方代号【${row.formulaCode}】信息`
  deviceFormulaFormRef.value.open(row)
}

//删除
const onDelete = (row: DeviceFormulaGetOutput) => {
  proxy.$modal
    .confirmDelete(`确定要删除配方代号为【${row.formulaCode}】?`)
    .then(async () => {
      await new DeviceFormulaApi().softDelete({ id: row.id }, { loading: true, showSuccessMessage: true })
      onQuery()
    })
    .catch(() => { })
}

//启用或禁用
const onSetEnable = (row: DeviceFormulaGetOutput & { loading: boolean }) => {
  return new Promise((resolve, reject) => {
    proxy.$modal
      .confirm(`确定要${row.enabled ? '禁用' : '启用'}配方代号为：【${row.formulaCode}】?`)
      .then(async () => {
        row.loading = true
        const res = await new DeviceFormulaApi()
          .setEnable({ deviceFormulaId: row.id, enabled: !row.enabled }, { showSuccessMessage: true })
          .catch(() => {
            reject(new Error('Error'))
          })
          .finally(() => {
            row.loading = false
          })
        if (res && res.success) {
          resolve(true)
        } else {
          reject(new Error('Cancel'))
        }
      })
      .catch(() => {
        reject(new Error('Cancel'))
      })
  })
}

//启用或禁用关联点位
const onSetLinkPointEnable = (row: DeviceFormulaGetOutput & { loading: boolean }) => {
  return new Promise((resolve, reject) => {
    proxy.$modal
      .confirm(`确定要${row.enabled ? '禁用' : '启用'}配方代号为：【${row.formulaCode}】?`)
      .then(async () => {
        row.loading = true
        const res = await new DeviceFormulaApi()
          .setLinkPointEnable({ deviceFormulaId: row.id, linkPointEnaled: !row.linkPoint }, { showSuccessMessage: true })
          .catch(() => {
            reject(new Error('Error'))
          })
          .finally(() => {
            row.loading = false
          })
        if (res && res.success) {
          resolve(true)
        } else {
          reject(new Error('Cancel'))
        }
      })
      .catch(() => {
        reject(new Error('Cancel'))
      })
  })
}

const onSizeChange = (val: number) => {
  state.pageInput.currentPage = 1
  state.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}
</script>